package com.example.ole.taskqueue.Q.base;


import com.example.ole.taskqueue.Print;

import java.util.concurrent.TimeUnit;

/**
 * Override functions to keep track of pending Normal and Event task number.
 *
 * @param <E> MUST be XTask
 */
public class PrioritizedRecordingQueue<E> extends PrioritizedBlockingQueueLimitBoundary {
    private static final String TAG = "PrioritizedRecordingQueue";
    private int mNormalTaskCount;
    private int mEventTaskCount;

    public PrioritizedRecordingQueue(int capacity) {
        super(capacity);
    }

    public int getNormalTaskCount() {
        return mNormalTaskCount;
    }

    public int getEventTaskCount() {
        return mEventTaskCount;
    }

    @Override
    public boolean offer(Object o) {
        boolean ret = super.offer(o);
        if (ret) {
            addOneTask(o);
        }
        return ret;
    }

    @Override
    public boolean remove(Object o) {
        boolean ret = super.remove(o);
        if (ret) {
            rmOneTask(o);
        }
        return ret;
    }

    @Override
    public Object take() throws InterruptedException {
        Object o = super.take();
        rmOneTask(o);
        return o;
    }

    @Override
    public Object poll(long timeout, TimeUnit unit) throws InterruptedException {
        Object o = super.poll(timeout, unit);
        if (o == null) {
            return null;
        }

        rmOneTask(o);
        return o;
    }

    private void addOneTask(Object o) {
        XTask rt = (XTask) o;
        if (rt.getEventType() == XEvent.NORMAL) {
            mNormalTaskCount++;
        } else {
            mEventTaskCount++;
        }
        Print.d(1, 1, TAG, String.format("Add %s. (Normal: %d Event: %d)", rt.identity(), mNormalTaskCount, mEventTaskCount));
    }

    private void rmOneTask(Object o) {
        XTask rt = (XTask) o;
        if (rt.getEventType() == XEvent.NORMAL) {
            mNormalTaskCount--;
        } else {
            mEventTaskCount--;
        }
        Print.d(1, 1, TAG, String.format("Rmv %s. (Normal: %d Event: %d)", rt.identity(), mNormalTaskCount, mEventTaskCount));
    }
}
